import math

from cryptography.fernet import Fernet

import random
import time
import os


class License:
    def encrypt(self, effective_days, ase_key, addresses=None, license_file=None):
        if effective_days < 0:
            print("license: error effective_days cannot be negative")
            return
        if addresses is None:
            addresses = []
        address_str = '$'.join(addresses)
        fernet = Fernet(ase_key)
        generate_date = str(int(time.time()))
        random_str = ''.join(random.sample('zyxwvutsrqponmlkjihgfedcba', 8))
        origin_str = str(effective_days) + '|' + generate_date + '|' + address_str + '|' + random_str
        encrypted = fernet.encrypt(origin_str.encode('utf-8'))
        with open(license_file, 'wb') as file:
            file.write(encrypted)
        return

    def decrypt(self, license_path, ase_key):
        file = open(license_path, 'r')
        try:
            encrypt_str = file.read()
        finally:
            file.close()
        fernet = Fernet(ase_key)
        decrypted = fernet.decrypt(encrypt_str).decode()
        decrypted_arr = decrypted.split('|')
        return decrypted_arr

    def get_mac_address(self):
        # 优先通过AICA_NIC_NAME读取mac地址
        nic_name = os.getenv("AICA_NIC_NAME")
        if nic_name is not None:
            mac_address = (os.popen('cat /host/sys/class/net/' + nic_name + '/address')
                           .read()
                           .replace('\r', '')
                           .replace('\n', ''))
            if mac_address is not None:
                return mac_address
        # 再通过主机网络模式 ip命令读取mac地址
        mac_address = (os.popen("ip link show `ip route |grep default|awk '{print $5}'` |grep ether | awk '{print $2}'")
                       .read()
                       .replace('\r', '')
                       .replace('\n', ''))
        return mac_address

    def verify_license(self, license_path, ase_key):
        decrypted_arr = self.decrypt(license_path, ase_key)
        effective_days = decrypted_arr[0]
        generate_date = decrypted_arr[1]

        # 校验地址
        addresses = decrypted_arr[2].split('$')
        addresses = list(filter(None, addresses))
        local_mac_address = self.get_mac_address()
        if local_mac_address is None:
            print("license: local_mac_address is None")
            return False

        exist = False
        for i in addresses:
            if i == local_mac_address:
                exist = True
                break
        if exist:
            # 如果为真，继续校验时间有效期
            print("license: address is valid")
        else:
            print("license: address is invalid")
            return False

        if int(effective_days) < 0:
            print("license error: effective_days cannot be negative")
            return False
        # 如果有效时间天数为0，则认为永久
        if int(effective_days) == 0:
            print("license: It is valid indefinitely.")
            return True

        # 校验时间
        if int(generate_date) + int(effective_days) * 24 * 60 * 60 > int(time.time()):
            print("license: there are {} days left before the license expires.".format(
                math.ceil((int(generate_date) + int(effective_days) * 24 * 60 * 60 - int(time.time())) / 24 / 60 / 60)))
            return True
        else:
            print("license: generate_date is expired")
            return False
